#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2023/10/31 16:44
# @Author  : huidong.bai
# @File    : RoutineTextFileParser.py
# @Software: PyCharm
# @Mail    : MasterBai2018@outlook.com
import re
import copy
import pdb


class RoutineTextFileParser:
    def __init__(self, file_path):
        self.file_path = file_path
        self.cases = []
        self.__parse_line()

    def __parse_line(self):
        with open(self.file_path, 'r') as file:
            lines = file.readlines()

        current_case = None
        start_line = None

        for line_number, line in enumerate(lines):
            if ">>>" in line.strip():
                repeat_count = int(line.strip().split()[1]) if len(line.strip().split()) > 1 else 1
                if current_case is not None:
                    current_case.append((start_line, line_number - 1))
                    self.cases.append(current_case)
                current_case = []
                start_line = (line_number, repeat_count)
            elif "<<<" in line.strip():
                if current_case is not None:
                    current_case.append((start_line, line_number - 1))
                    self.cases.append(current_case)
                current_case = None

    def get_cases(self):
        case_list = []
        for case_number, case in enumerate(self.cases):
            start_info, end_line = case[0]
            start_line, repeat_count = start_info
            case_content = self.get_case_content(start_line+1, end_line+2)
            case, _ = self.parse_case(case_content)
            testcase = {"index": f"{start_line+1}-{end_line+2}", "content": case}
            for i in range(repeat_count):
                case_list.append(copy.deepcopy(testcase))
        return case_list

    def get_case_filter(self, tag=None):
        if not tag:
            return self.get_cases()
        start, end = [int(i) for i in tag.split("-")]
        case_list = []
        case_content = self.get_case_content(start, end)
        case, repeat_count = self.parse_case(case_content)
        testcase = {"index": f"{start}-{end}", "content": case}
        for i in range(repeat_count):
            case_list.append(copy.deepcopy(testcase))
        return case_list

    @staticmethod
    def parse_case(content):
        control_list = []
        for line in content:
            info = line.strip()
            if ">>>" in info:
                repeat_count = int(info.split()[1]) if len(info.split()) > 1 else 1
                continue
            if line.isspace() or info[0] == "#" or info[:2] == "//" or "<<<" in info:
                continue
            re_list = re.split(r'\t+', info)
            line_info = [item.strip() for item in re_list if item.strip()]
            while len(line_info) < 2:
                line_info.append(None)
            terminal, params = line_info
            pattern = r"\[(.*?)\](.*)"
            client, cmd = re.match(pattern, terminal).groups()
            if params:
                split_str = params.split()
                if split_str[-1].startswith('<') and split_str[-1].endswith('>'):
                    timestamp = int(split_str[-1][1:-1])
                    param_list = split_str[:-1]
                else:
                    timestamp = None
                    param_list = split_str
            else:
                timestamp = None
                param_list = []
            control_list.append((client, timestamp, cmd, param_list))
        return control_list, repeat_count

    def get_case_content(self, start_line, end_line):
        with open(self.file_path, 'r') as file:
            lines = file.readlines()
        return lines[start_line-1:end_line]


if __name__ == '__main__':
    parser = RoutineTextFileParser('routine.txt')
    print(parser.get_case_filter())
    print(parser.get_case_filter("10-18"))
